from django.shortcuts import render, HttpResponse
from .models import *


# Create your views here.
# 一对多关系
def add_user(request):
    # 给usertype添加数据
    # user_types = ['青铜', '白银', '钻石', '大师', '王者']
    # for name in user_types:
    #     UserType.objects.get_or_create(name=name)

    # 给user添加数据
    for i in range(11, 30):
        # user_type_id 为对象
        # User.objects.create(name=f'张三{i}', age=i, user_type_id=i % 5+1)

        # user_type 为类型
        User.objects.create(name=f'李四{i}', age=i + 100, user_type=UserType.objects.get(pk=i % 5 + 1))

    return HttpResponse('添加成功！！！')


# 删除数据
def del_user(request):
    # 删除用户数据
    # User.objects.filter(id=1).delete()

    # 删除user_type
    UserType.objects.filter(id=2).delete()
    return HttpResponse("删除成功！！！")


# 修改数据
def update_user(request):
    # 修改UserType
    # UserType.objects.filter(id=1).update(name='黑铜')

    # 修改User
    User.objects.filter(id=2).update(age=10000)

    # 跨表修改

    return HttpResponse('修改成功！！！')


# 查询数据
def select_user(request):
    # 正向查询: 从user表去查找usertype表
    print(User.objects.get(id=2).user_type.name)

    # 反向查询: 从usertype表去找user表
    print(UserType.objects.get(pk=1).id, UserType.objects.get(pk=1).name)

    # user_set : 内部自动生成的属性 可以让你反向查询到所有的User集合
    # print(UserType.objects.get(pk=1).user_set)  # App.User.None
    # print(UserType.objects.get(pk=1).user_set.all())  # QuerySet
    # [<User: User object (5)>, <User: User object (10)>, <User: User object (15)>,
    # <User: User object (24)>, <User: User object (29)>, <User: User object (34)>]>

    print('*' * 60)
    # 在filter中 还可以这么用
    # 比如：查询用户类型名称为白银的所有用户
    # print(User.objects.filter(user_type=UserType.objects.get(name='白银')))

    # print(User.objects.filter(user_type=UserType.objects.get(id=3)))
    # print(User.objects.filter(user_type__name='钻石'))
    print('*' * 60)

    # related_name:  关联的名称
    print(UserType.objects.get(pk=1).users.all())
    return HttpResponse('查询成功！！！')
